package com.xingfei.blog.result;

import com.xingfei.blog.constants.ErrorConstants;

/**
 * Created with IntelliJ IDEA.
 * 构造返回结果对象，在dubbo返回所有结果集，均通过此对象进行构造返回结果
 *
 * @author: chenxingfei
 * @time: 2017/1/23  15:38
 * To change this template use File | Settings | File Templates.
 */
public class ResultConstructor {


    /**
     * 返回成功信息
     *
     * @param obj
     * @return
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    public static ServiceResult buildSuccessResult(Object obj) {
        ServiceResult result = new ServiceResult();
        result.setResult(obj);
        result.setCode(ErrorConstants.RES_SUCCESS);
        result.setResultCode(null);
        result.setErrMsg(null);
        return result;
    }

    /**
     * 封装结构集数据
     * @param <T>
     * @param <T>
     * @param code
     * @param msg
     * @param obj
     * @return
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    public static ServiceResult buildSuccessResult(String code, String msg, Object obj) {
        ServiceResult result = new ServiceResult();
        result.setResult(obj);
        result.setResultCode(code);
        result.setCode(ErrorConstants.RES_SUCCESS);
        result.setErrMsg(msg);
        return result;
    }

    /**
     * 封装结构集数据
     *
     * @param <T>
     * @param <T>
     * @param code
     * @param msg
     * @param obj
     * @return
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    public static ServiceResult buildSuccessResult(Object obj, int code, String msg) {
        ServiceResult result = new ServiceResult();
        result.setResult(obj);
        result.setCode(code);
        result.setErrMsg(msg);
        return result;
    }

    /**
     * 返回应用错误信息，包含网络和数据库错误，runtime异常等
     *
     * @param msg
     * @return
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    public static ServiceResult buildRunTimeErrResult(String... msg) {
        ServiceResult result = new ServiceResult();
        result.setResult(null);
        result.setResultCode(null);
        result.setCode(ErrorConstants.RES_RUNTIME);
        result.setErrMsg(buildString(msg));
        return result;
    }

    /**
     * 返回业务逻辑错误信息，包含参数错误等
     *
     * @param msg
     * @return
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    public static ServiceResult buildServiceErrResult(String resultCode, String... msg) {
        ServiceResult result = new ServiceResult();
        result.setResult(null);
        result.setResultCode(resultCode);
        result.setCode(ErrorConstants.RES_SERVICE);
        result.setErrMsg(buildString(msg));
        return result;
    }

    /**
     * 字符串链接
     *
     * @param str
     * @return
     */
    public static String buildString(String... str) {
        StringBuilder buf = new StringBuilder();
        for (String s : str) {
            buf.append(s);
        }
        return buf.toString();
    }

}
